#include "InSdkConnectWiFi.h"
#include "InPerLed.h"
#include "InSdkCallbackFunction.h"
#include "InSdkWifiScanner.h"

#define DEF_TAG             "ConnectWifi"

Com_void InSdkWiFiConnect_ExecCmd(Com_ps8 pCmd)
{
//    PRT_INFO(DEF_TAG,"%s\n", pCmd);
    Ext_InSdkTcpSystem_Cmd(pCmd);
}

Com_void Ext_InSdkWiFi_Connect(Com_ps8 ssid,Com_ps8 passwd)
{
    if(ssid == NULL)
    {
        PRT_WARN(DEF_TAG,"no ssid\n");
        return;
    }

    char tmpCmd[100] = {0};
    int ret = 0;

    InSdkWiFiConnect_ExecCmd("killall -9 hostapd");
    InSdkWiFiConnect_ExecCmd("killall -9 udhcpd");
    sleep(1);

    Ext_InPerLed_SetSta(DEF_COM_TRUE);
    Ext_InComFile_Creat(DEF_FLAG_NET_CONNECTING);

    if(Ext_InComFile_Access(DEF_FILE_SAVE_CONF) == DEF_COM_FILE_EXIST)
    {
        Com_s8 cp_buf[128];

        memset(cp_buf,0,sizeof(cp_buf));
        snprintf(cp_buf,sizeof(cp_buf),"cp %s %s",DEF_FILE_SAVE_CONF,DEF_WPA_CONF_PATH);
        InSdkWiFiConnect_ExecCmd(cp_buf);

        while(Ext_InComFile_Access(DEF_WPA_CONF_PATH) == DEF_COM_FILE_NOT_EXIST)
        {
            usleep(10 * 1000);
        }

        snprintf(tmpCmd,100,"wifi_mode_switch.sh STA %s visible_ssid",DEF_COM_WLAN_DEV);
        InSdkWiFiConnect_ExecCmd(tmpCmd);

        goto exit_wifi;
    }

    Ext_InSdkWiFiScan_SetType(SCAN_WIFI_ON);
    int wifi_mode = WIFI_ENCRYPT_MODE_UNKONW;
    int wifi_scan_count = 0;

    ret = Ext_InSdkWiFiScan_InitInternel(DEF_COM_WLAN_DEV);
    if (ret != 0)
    {
        PRT_ERR(DEF_TAG,"init wifi internel failed !\n");
    }
    PRT_NORMAL("scan dev is %s\n",DEF_COM_WLAN_DEV);

    while(((wifi_mode = Ext_InSdkWiFiScan_CheckEncrypt(ssid)) == -1) && (wifi_scan_count < MAX_WIFI_LIST))
    {
        usleep(100 * 1000);
        wifi_scan_count++;
    }

    PRT_NORMAL("check wifi mode: %d\n",wifi_mode);
    Ext_InSdkWiFiScan_Stop();

    if (wifi_scan_count >= MAX_WIFI_LIST)
    {
        Ext_InSdkWiFiScan_SaveHideCfgFile(ssid,passwd);

        snprintf(tmpCmd,100,"wifi_mode_switch.sh STA %s hide_ssid",DEF_COM_WLAN_DEV);
        InSdkWiFiConnect_ExecCmd(tmpCmd);
    }
    else
    {
        if ((wifi_mode != WIFI_ENCRYPT_MODE_OPEN) && (wifi_mode != WIFI_ENCRYPT_MODE_WEP) &&
            (wifi_mode != WIFI_ENCRYPT_MODE_WPA2))
        {
            Ext_InSdkWiFiScan_SaveHideCfgFile(ssid,passwd);
            snprintf(tmpCmd,100,"wifi_mode_switch.sh STA %s hide_ssid",DEF_COM_WLAN_DEV);
        }
        else
        {
            ret = Ext_InSdkWiFiScan_SaveCfgFile(DEF_WPA_CONF_PATH,ssid,passwd,wifi_mode);
            if (ret != 0)
            {
                PRT_ERR(DEF_TAG,"wifi scan cfgfile error !!!! \n");
            }

            snprintf(tmpCmd,100,"wifi_mode_switch.sh STA %s visible_ssid",DEF_COM_WLAN_DEV);
        }
        InSdkWiFiConnect_ExecCmd(tmpCmd);
    }

exit_wifi:
    return;
}
